package com.xiao.train.business.service;

import com.xiao.train.business.domain.ConfirmOrder;
import com.xiao.train.business.domain.DailyTrainSeat;
import com.xiao.train.business.domain.DailyTrainTicket;
import com.xiao.train.business.enums.ConfirmOrderStatusEnum;
import com.xiao.train.business.feign.MemberFeign;
import com.xiao.train.business.mapper.ConfirmOrderMapper;
import com.xiao.train.business.mapper.DailyTrainSeatMapper;
import com.xiao.train.business.mapper.cust.DailyTrainTicketMapperCust;
import com.xiao.train.business.req.ConfirmOrderTicketReq;
import com.xiao.train.common.req.MemberTicketReq;
import com.xiao.train.common.resp.CommonResp;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AfterConfirmOrderService {
    @Resource
    MemberFeign memberFeign;

    @Resource
    DailyTrainSeatMapper dailyTrainSeatMapper;

    @Resource
    DailyTrainTicketMapperCust dailyTrainTicketMapperCust;

    @Resource
    ConfirmOrderMapper confirmOrderMapper;

//    @GlobalTransactional //全局事务
    public void afterDoConfirm(DailyTrainTicket dailyTrainTicket, List<DailyTrainSeat> finalSeatList,
                               List<ConfirmOrderTicketReq> tickets, ConfirmOrder confirmOrder) throws Exception {
        log.info("Seata的全局事务ID: {}", RootContext.getXID());
        for (int j = 0; j < finalSeatList.size(); j++) {
            DailyTrainSeat dailyTrainSeat = finalSeatList.get(j);
            DailyTrainSeat seatForUpdate = new DailyTrainSeat();
            seatForUpdate.setId(dailyTrainSeat.getId());
            seatForUpdate.setSell(dailyTrainSeat.getSell());
            seatForUpdate.setUpdateTime(new Date());
            dailyTrainSeatMapper.updateByPrimaryKeySelective(seatForUpdate);

            //假设10个站,购买5-8站
            //原售:001000001
            //购买:000011100
            //新售:001011101
            //影响:001X111X1
            Integer maxStartIndex = dailyTrainTicket.getStartIndex();
            int minEndIndex = dailyTrainTicket.getEndIndex() - 1;
            char[] chars = seatForUpdate.getSell().toCharArray();
            int minStartIndex = maxStartIndex, maxEndIndex = minEndIndex;
            if (maxStartIndex - 1 >= 0) {
                for (int i = maxStartIndex - 1; i >= 0; i--) {
                    if (chars[i] == '0')
                        minStartIndex = i;
                    else
                        break;
                }
            }
            if (minEndIndex + 1 < chars.length) {
                for (int i = minEndIndex + 1; i < chars.length; i++) {
                    if (chars[i] == '0')
                        maxEndIndex = i;
                    else
                        break;
                }
            }
            minEndIndex++;
            maxEndIndex++;
            log.info("影响出发站区间: {}-{}", minStartIndex, maxStartIndex);
            log.info("影响到达站区间: {}-{}", minEndIndex, maxEndIndex);
            dailyTrainTicketMapperCust.updateCountBySell(
                    dailyTrainSeat.getDate(),
                    dailyTrainSeat.getTrainCode(),
                    dailyTrainSeat.getSeatType(),
                    minStartIndex,
                    maxStartIndex,
                    minEndIndex,
                    maxEndIndex);

            // 调用会员服务接口，为会员增加一张车票
            MemberTicketReq memberTicketReq = new MemberTicketReq();
            memberTicketReq.setMemberId(confirmOrder.getMemberId());
            memberTicketReq.setPassengerId(tickets.get(j).getPassengerId());
            memberTicketReq.setPassengerName(tickets.get(j).getPassengerName());
            memberTicketReq.setTrainDate(dailyTrainTicket.getDate());
            memberTicketReq.setTrainCode(dailyTrainTicket.getTrainCode());
            memberTicketReq.setCarriageIndex(dailyTrainSeat.getCarriageIndex());
            memberTicketReq.setSeatRow(dailyTrainSeat.getRow());
            memberTicketReq.setSeatCol(dailyTrainSeat.getCol());
            memberTicketReq.setStartStation(dailyTrainTicket.getStart());
            memberTicketReq.setStartTime(dailyTrainTicket.getStartTime());
            memberTicketReq.setEndStation(dailyTrainTicket.getEnd());
            memberTicketReq.setEndTime(dailyTrainTicket.getEndTime());
            memberTicketReq.setSeatType(dailyTrainSeat.getSeatType());
            CommonResp commonResp = memberFeign.save(memberTicketReq);
            log.info("调用member接口，返回：{}", commonResp);
        }
        String status = finalSeatList.size() > 0 ? ConfirmOrderStatusEnum.SUCCESS.getCode() : ConfirmOrderStatusEnum.EMPTY.getCode();
        // 更新订单状态为成功
        ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();
        confirmOrderForUpdate.setId(confirmOrder.getId());
        confirmOrderForUpdate.setUpdateTime(new Date());
        confirmOrderForUpdate.setStatus(status);
        confirmOrderMapper.updateByPrimaryKeySelective(confirmOrderForUpdate);
    }
}
